/**
 * Created by henian.xu on 2018/10/9.
 *
 */

class RouterInterceptors {
    constructor(router, store, GlobalVar) {
        this.router = router;
        this.store = store;
        this.GlobalVar = GlobalVar;

        router.beforeEach(this.beforeEach.bind(this));
    }
    initAppData() {
        return new Promise((resolve, reject) => {
            if (this.GlobalVar.isInitAppDataEnd) {
                resolve();
                return;
            }
            Promise.all([
                this.store.dispatch('global/menu/getMenuData'),
                this.store.dispatch('global/power/getMenuResource'),
                // Store.dispatch('global/app/getAppList'),
            ])
                .then(() => {
                    this.GlobalVar.isInitAppDataEnd = true;
                    resolve();
                })
                .catch(error => {
                    const { response } = error;
                    if (typeof response === 'object') {
                        const { status } = response;
                        if (status === 401) {
                            reject(error);
                            return;
                        }
                    }
                    // GlobalVar.isInitAppDataEnd = true;
                    const err = {
                        to: '/error/500',
                        query: {
                            message: '应用级数据初始化失败',
                        },
                    };
                    reject(err);
                });
        });
    }

    /**
     * 路由前拦截
     * @param to
     * @param from
     * @param next
     */
    beforeEach(to, from, next) {
        if (to.path === '/login') {
            next();
            return;
        }
        this.initAppData()
            .catch(error => {
                if (error.to) {
                    const toData = {
                        path: error.to,
                        query: error.query,
                    };
                    next(toData);
                } else {
                    next();
                }
            })
            .then(next);
        next();
    }
}

export default RouterInterceptors;
